package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"rpc/model/mysql"
	"rpc/pkg"
	"strconv"

	"rpc/internal/svc"
	"rpc/turn"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderCreateLogic {
	return &OrderCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderCreateLogic) OrderCreate(in *turn.OrderCreateRequest) (*turn.OrderCreateResponse, error) {
	// todo: add your logic here and delete this line
	g := mysql.Goods{}
	err := g.FindGoods(in.GoodsId)
	if err != nil {
		return nil, err
	}

	if g.GoodsStock < int(in.Num) {
		logx.Error("库存不足")
		return nil, fmt.Errorf("库存不足")
	}
	orderSn := uuid.NewString()
	Amount := g.GoodsPrice * float64(in.Num)
	o := mysql.Order{
		OrderSn:     orderSn,
		UserId:      in.Userid,
		GoodsId:     in.GoodsId,
		OrderAmount: Amount,
	}
	err = o.Create()
	if err != nil {
		logx.Error("订单创建失败")
		return nil, fmt.Errorf("订单创建失败")
	}
	amount := strconv.FormatFloat(Amount, 'f', 1, 64)
	pay := pkg.Pay(g.GoodsName, orderSn, amount)

	return &turn.OrderCreateResponse{OrderId: int64(o.ID), Url: pay}, nil
}
